package org.example.myleet.p1624;

public class Solution {
    public int maxLengthBetweenEqualCharacters(String s) {
        int[] characterLastIndex = new int[26];
        //从尾到头找到每一种字符最后一次出现的位置
        for (int i = 0; i < 26; ++i) {
            characterLastIndex[i] = -1;
        }
        char[] sCharArr = s.toCharArray();
        for (int i = sCharArr.length - 1; i >= 0; --i) {
            int c = sCharArr[i] - 'a';
            if (characterLastIndex[c] < 0) {
                characterLastIndex[c] = i;
            }
        }
        //遍历，利用记忆化的字符最后一次出现的位置计算相同字符之间最大的长度
        int maxLen = -1;
        for (int i = 0; i < sCharArr.length; ++i) {
            char c = sCharArr[i];
            int index = characterLastIndex[c - 'a'];
            if (index >= 0 && index != i) {
                maxLen = Math.max(maxLen, index - 1 - i);
            }
        }
        return maxLen;
    }
}
